package com.example.administrator.yanfoxconn.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.administrator.yanfoxconn.R;
import com.example.administrator.yanfoxconn.bean.ComScanViewMessage;
import com.example.administrator.yanfoxconn.bean.GAWork;
import com.example.administrator.yanfoxconn.bean.JGBaseMessage;
import com.example.administrator.yanfoxconn.bean.SelectModel;
import com.example.administrator.yanfoxconn.constant.Constants;
import com.example.administrator.yanfoxconn.constant.FoxContext;
import com.example.administrator.yanfoxconn.constant.ImageCaptureManager;
import com.example.administrator.yanfoxconn.intent.PhotoPickerIntent;
import com.example.administrator.yanfoxconn.intent.PhotoPreviewIntent;
import com.example.administrator.yanfoxconn.utils.BaseActivity;
import com.example.administrator.yanfoxconn.utils.DateTimePickDialog30Util;
import com.example.administrator.yanfoxconn.utils.DateTimePickDialogUtil;
import com.example.administrator.yanfoxconn.utils.FileUtil;
import com.example.administrator.yanfoxconn.utils.HttpConnectionUtil;
import com.example.administrator.yanfoxconn.utils.HttpUtils;
import com.example.administrator.yanfoxconn.utils.ImageZipUtils;
import com.example.administrator.yanfoxconn.utils.TimeDateUtils;
import com.example.administrator.yanfoxconn.utils.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.json.JSONArray;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @Description 消毒劑配比 主界面
 * @Author song
 * @Date 6/17/21 8:41 AM
 */
public class JGUpMainActivity extends BaseActivity implements View.OnClickListener{

    private final int MESSAGE_TOAST = 2;//showToast
    private final int MESSAGE_SET_TEXT = 1;//獲取狀態后,設置控件內容
    private final int MESSAGE_NOT_NET = 3;//網絡問題
    private final int MESSAGE_UP = 4;//提交响应
    private final int MESSAGE_TOAST_NULL=0;//下拉列表信息缺失

    private String initStartDateTime,initStartDateTime1; // 初始化开始时间
    private Date selectTime = null;//所選時間
    private Date curDate = null;//當前時間
    private String curDates;//當前時間
    private SimpleDateFormat formatter;


    @BindView(R.id.btn_title_left)
    Button btnBack;//返回
    @BindView(R.id.tv_title)
    TextView tvTitle;//標題
    @BindView(R.id.btn_title_right)
    Button btnCheck;//提交

    @BindView(R.id.sp_address)
    Spinner spAddress;//消毒地點
    @BindView(R.id.sp_device)
    Spinner spDevice;//消毒設備
    @BindView(R.id.sp_method)
    Spinner spMethod;//消毒方式
    @BindView(R.id.sp_name)
    Spinner spName;//消毒劑名稱
    @BindView(R.id.tv_open_date)
    TextView tvOpenDate;//開瓶時間
    @BindView(R.id.tv_invalid_date)
    TextView tvInvalidDate;//失效期限
    @BindView(R.id.et_pihao)
    EditText etPihao;//消毒劑批號
    @BindView(R.id.et_cheng_fen)
    EditText etChenFen;//有效成分含量
    @BindView(R.id.sp_amount_xs)
    Spinner spXS;//消毒劑用量
//    @BindView(R.id.sp_amount_water)
//    Spinner spWater;//加水量
    @BindView(R.id.tv_nongdu)
    TextView tvNongDu;//終濃度
    @BindView(R.id.tv_unit)
    TextView tvUnit;//實施單位
    @BindView(R.id.tv_worker)
    TextView tvWork;//配置人員
    @BindView(R.id.tv_date)
    TextView tvDate;//配置時間
    @BindView(R.id.iv_empty)
    ImageView ivEmpty;//空白图片占位
    @BindView(R.id.gv_photo)
    GridView gvPhoto;//图片显示区域
    @BindView(R.id.tr_amount_xs)
    TableRow tr_xs;//消毒劑用量/水量行
//    @BindView(R.id.tr_amount_water)
//    TableRow tr_water;//加水量行
    @BindView(R.id.tr_nongdu)
    TableRow tr_nongdu;//終濃度行
    @BindView(R.id.btn_up)
    Button btnUp;//提交
    private static final int REQUEST_CAMERA_CODE = 11;
    private static final int REQUEST_PREVIEW_CODE = 22;
;
    private ArrayList<String> imagePaths = null;//圖片未壓縮地址
    private ArrayList<String> imgZipPaths = new ArrayList<String>();//圖片壓縮后地址
    private ImageCaptureManager captureManager; // 相机拍照处理类
    private GridAdapter gridAdapter;

    private List<JGBaseMessage> addressS,deviceS,methodS,nameS,xsS;//,waterS
    private String address,device,method,name,xs,water;
//    private int nong=0;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jg_up_main);
        ButterKnife.bind(this);

        tvTitle.setText("記錄界面");
        btnBack.setText("返回");
        btnCheck.setText("記錄");
        btnUp.setOnClickListener(this);
        btnCheck.setVisibility(View.VISIBLE);
        btnCheck.setOnClickListener(this);
        btnBack.setOnClickListener(this);
//        tvNongDu.setOnClickListener(this);
        tvInvalidDate.setOnClickListener(this);
        tvOpenDate.setOnClickListener(this);

        formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        SimpleDateFormat formatterUse = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
        curDate = new Date(System.currentTimeMillis());
        //获取当前时间
        initStartDateTime = formatterUse.format(curDate);
        initStartDateTime1 = formatterUse.format(curDate);
        tvInvalidDate.setText("選擇時間");
        tvOpenDate.setText("選擇時間");
        tvDate.setText(formatter.format(curDate));
        curDates = formatter.format(curDate);

    Log.e("--------1---","fff原因");
    getMessage();
        ivEmpty.setOnClickListener(this);
        int cols = getResources().getDisplayMetrics().widthPixels / getResources().getDisplayMetrics().densityDpi;
        cols = cols < 4 ? 4 : cols;
        gvPhoto.setNumColumns(cols);

        // preview
        gvPhoto.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position == imagePaths.size()) {
                    PhotoPickerIntent intent = new PhotoPickerIntent(JGUpMainActivity.this);
                    intent.setSelectModel(SelectModel.MULTI);
                    intent.setShowCarema(true); // 是否显示拍照
                    intent.setMaxTotal(3); // 最多选择照片数量，默认为3
                    intent.setSelectedPaths(imagePaths); // 已选中的照片地址， 用于回显选中状态

                    startActivityForResult(intent, REQUEST_CAMERA_CODE);
                } else {
                    PhotoPreviewIntent intent = new PhotoPreviewIntent(JGUpMainActivity.this);
                    intent.setCurrentItem(position);
                    intent.setPhotoPaths(imagePaths);
                    startActivityForResult(intent, REQUEST_PREVIEW_CODE);
                }
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

            switch (requestCode) {
                // 选择照片
                case REQUEST_CAMERA_CODE:
                    loadAdpater(data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT));
                    break;
                // 预览
                case REQUEST_PREVIEW_CODE:
                    loadAdpater(data.getStringArrayListExtra(PhotoPreviewActivity.EXTRA_RESULT));
                    break;
                // 调用相机拍照
                case ImageCaptureManager.REQUEST_TAKE_PHOTO:
                    if (captureManager.getCurrentPhotoPath() != null) {
                        captureManager.galleryAddPic();

                        ArrayList<String> paths = new ArrayList<>();
                        paths.add(captureManager.getCurrentPhotoPath());
                        loadAdpater(paths);
                        Log.e("==========", paths.get(1));
                    }
                    break;

            }
        }
    }

    private void loadAdpater(ArrayList<String> paths) {
        if (imagePaths == null) {
            imagePaths = new ArrayList<>();
        }
        imagePaths.clear();
        imagePaths.addAll(paths);

        if (paths.size() > 0) {
            ivEmpty.setVisibility(View.GONE);
        } else {
            ivEmpty.setVisibility(View.VISIBLE);
        }

        try {
            JSONArray obj = new JSONArray(imagePaths);
            Log.e("--", obj.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (gridAdapter == null) {
            gridAdapter = new GridAdapter(imagePaths);
            gvPhoto.setAdapter(gridAdapter);
            Log.e("----------------", "ddd==" + imagePaths.size());
        } else {
            gridAdapter.notifyDataSetChanged();
        }
    }

    //獲取下拉列表信息
    private void getMessage(){
        showDialog();
        final String url = Constants.HTTP_XS_MAKE_RECORD_SERVLET;

        new Thread() {
            @Override
            public void run() {
                //把网络访问的代码放在这里
                String result = HttpUtils.queryStringForGet(url);

                dismissDialog();
                Log.e("---------", "==fff===" + url);
                Gson gson = new Gson();
                if (result != null) {
                    Log.e("---------", "result==fff===" + result);

                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {
                        JsonArray array1 = jsonObject.get("data1").getAsJsonArray();
                        addressS = new ArrayList<JGBaseMessage>();

                        for (JsonElement type : array1) {
                            JGBaseMessage humi = gson.fromJson(type, JGBaseMessage.class);
                            addressS.add(humi);
                        }
                        JsonArray array2 = jsonObject.get("data2").getAsJsonArray();
                        deviceS = new ArrayList<JGBaseMessage>();

                        for (JsonElement type : array2) {
                            JGBaseMessage humi = gson.fromJson(type, JGBaseMessage.class);
                            deviceS.add(humi);
                        }
                        JsonArray array3 = jsonObject.get("data3").getAsJsonArray();
                        methodS = new ArrayList<JGBaseMessage>();

                        for (JsonElement type : array3) {
                            JGBaseMessage humi = gson.fromJson(type, JGBaseMessage.class);
                            methodS.add(humi);
                        }
                        JsonArray array4 = jsonObject.get("data4").getAsJsonArray();
                        nameS = new ArrayList<JGBaseMessage>();

                        for (JsonElement type : array4) {
                            JGBaseMessage humi = gson.fromJson(type, JGBaseMessage.class);
                            nameS.add(humi);
                        }
                        JsonArray array5 = jsonObject.get("data5").getAsJsonArray();
                        xsS = new ArrayList<JGBaseMessage>();

                        for (JsonElement type : array5) {
                            JGBaseMessage humi = gson.fromJson(type, JGBaseMessage.class);
                            xsS.add(humi);
                        }
//                        JsonArray array6 = jsonObject.get("data6").getAsJsonArray();
//                        waterS = new ArrayList<JGBaseMessage>();
//
//                        for (JsonElement type : array6) {
//                            JGBaseMessage humi = gson.fromJson(type, JGBaseMessage.class);
//                            waterS.add(humi);
//                        }

                        Message message = new Message();
                        message.what = MESSAGE_SET_TEXT;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);

                    } else{
                        Message message = new Message();
                        message.what = MESSAGE_TOAST_NULL;//下拉列表信息缺失;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    }
                }
            } }.start();
    }


   private  List<String> addressL,deviceL,methodL,nameL,xsL;//,xsUnit,waterUnit,waterL
    private String jxs,jwater;//用於計算；
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case MESSAGE_TOAST://Toast彈出

                    ToastUtils.showLong(JGUpMainActivity.this, msg.obj.toString());
                    finish();
                    break;
                case MESSAGE_TOAST_NULL://下拉列表信息缺失
                    ToastUtils.showLong(JGUpMainActivity.this, "下拉列表信息缺失");
                    finish();
                    break;
                case MESSAGE_SET_TEXT://text賦值
                    tvUnit.setText(FoxContext.getInstance().getDep());
                    tvWork.setText(FoxContext.getInstance().getName());
                    addressL= new ArrayList<>();
                    deviceL= new ArrayList<>();
                    methodL= new ArrayList<>();
                    nameL= new ArrayList<>();
                    xsL = new ArrayList<>();
//                    xsUnit = new ArrayList<>();
//                    waterL = new ArrayList<>();
//                    waterUnit = new ArrayList<>();
                    if (addressS.size()>0){
                        addressL.add("請選擇！");
                        for (int i = 0;i<addressS.size();i++){
                            addressL.add(addressS.get(i).getNAME());
                        }
                    }
                    if (deviceS.size()>0){
                        for (int i = 0;i<deviceS.size();i++){
                            deviceL.add(deviceS.get(i).getNAME());
                        }
                    }
                    if (methodS.size()>0){
                        for (int i = 0;i<methodS.size();i++){
                            methodL.add(methodS.get(i).getNAME());
                        }
                    }
                    if (nameS.size()>0){
                        for (int i = 0;i<nameS.size();i++){
                            nameL.add(nameS.get(i).getNAME());
                        }
                    }
                    if (xsS.size()>0){
                        for (int i = 0;i<xsS.size();i++){
                            xsL.add(xsS.get(i).getNAME());
//                            xsUnit.add(xsS.get(i).getNAME());
                        }
                    }
//                    if (waterS.size()>0){
//                    for (int i = 0;i<waterS.size();i++){
//                        waterL.add(waterS.get(i).getNAME()+waterS.get(i).getUNIT());
//                        waterUnit.add(waterS.get(i).getNAME());
//                    }
//                }
                    spXS.setAdapter(new ArrayAdapter<String>(JGUpMainActivity.this, android.R.layout.simple_list_item_1, xsL));
                    spXS.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                            xs = xsL.get(position);
//                            jxs = xsUnit.get(position);
//                            tvNongDu.setTextColor(getResources().getColor(R.color.design_default_color_primary_dark));
//                            tvNongDu.setText("請點擊計算！");
//                            nong=0;
                       }
                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {
                        }
                    });
//                    spWater.setAdapter(new ArrayAdapter<String>(JGUpMainActivity.this, android.R.layout.simple_list_item_1, waterL));
//                    spWater.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
//                        @Override
//                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                            water = waterL.get(position);
//                            jwater = waterUnit.get(position);
//                            if ((int)(Float.valueOf(1)/(Float.valueOf(jxs)/(Float.valueOf(jwater)*1000)))<=100) {
//                                tvNongDu.setTextColor(getResources().getColor(R.color.blank));
//                                tvNongDu.setText("1：" + ((int) (Float.valueOf(1) / (Float.valueOf(jxs) / (Float.valueOf(jwater) * 1000)))));
//                          nong=1;
//                            }else{
//                                tvNongDu.setText("配比異常請重新選擇！");
//                                tvNongDu.setTextColor(getResources().getColor(R.color.color_d73d19));
//                                nong=0;
//                            }
//                        }
//                        @Override
//                        public void onNothingSelected(AdapterView<?> parent) {
//                        }
//                    });
                    spAddress.setAdapter(new ArrayAdapter<String>(JGUpMainActivity.this, android.R.layout.simple_spinner_item, addressL));
                    spAddress.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                            address = addressL.get(position);
                        }
                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {
                        }
                    });
                    spDevice.setAdapter(new ArrayAdapter<String>(JGUpMainActivity.this, android.R.layout.simple_list_item_1, deviceL));
                    spDevice.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                            device = deviceL.get(position);
                        }
                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {
                        }
                    });
                    spMethod.setAdapter(new ArrayAdapter<String>(JGUpMainActivity.this, android.R.layout.simple_list_item_1, methodL));
                    spMethod.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                            method = methodL.get(position);
                        }
                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {
                        }
                    });
                    spName.setAdapter(new ArrayAdapter<String>(JGUpMainActivity.this, android.R.layout.simple_list_item_1, nameL));
                    spName.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                        @Override
                        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                            name = nameL.get(position);
                            if (name.equals("酒精")){
                                tr_nongdu.setVisibility(View.GONE);
//                                tr_water.setVisibility(View.GONE);
                                tr_xs.setVisibility(View.GONE);
                            }else{
                                tr_nongdu.setVisibility(View.VISIBLE);
//                                tr_water.setVisibility(View.VISIBLE);
                                tr_xs.setVisibility(View.VISIBLE);
                            }
                        }
                        @Override
                        public void onNothingSelected(AdapterView<?> parent) {
                        }
                    });
                    break;
                case MESSAGE_UP://提交響應
                    worningAlert(msg.obj.toString(),MESSAGE_TOAST);
//                    ToastUtils.showLong(CrossScanActivity.this, msg.obj.toString());

                    break;
                case MESSAGE_NOT_NET://Toast彈出
btnUp.setClickable(true);
                    ToastUtils.showLong(JGUpMainActivity.this, "网络问题请稍后重试！");
//                    finish();
                    break;
            }
            super.handleMessage(msg);
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_empty:
                PhotoPickerIntent intent = new PhotoPickerIntent(JGUpMainActivity.this);
                intent.setSelectModel(SelectModel.MULTI);
                intent.setShowCarema(true); // 是否显示拍照
                intent.setMaxTotal(3); // 最多选择照片数量，默认为9
                intent.setSelectedPaths(imagePaths); // 已选中的照片地址， 用于回显选中状态

                startActivityForResult(intent, REQUEST_CAMERA_CODE);
                break;
            case R.id.tv_invalid_date:

                DateTimePickDialogUtil dateTimeS = new DateTimePickDialogUtil(
                        JGUpMainActivity.this, initStartDateTime);

                dateTimeS.dateTimePicKDialog(tvInvalidDate, "", "");
                break;
            case R.id.tv_open_date:

                DateTimePickDialogUtil dateTimeOpen = new DateTimePickDialogUtil(
                        JGUpMainActivity.this, initStartDateTime1);

                dateTimeOpen.dateTimePicKDialog(tvOpenDate, "", "");
                break;

            case R.id.btn_title_right://提交
//                if (etPihao.getText().toString().equals("")){
//                    ToastUtils.showLong(JGUpMainActivity.this,"請輸入正確批號信息！");
//                } else if (etChenFen.getText().toString().equals("")){
//                    ToastUtils.showLong(JGUpMainActivity.this,"請輸入正確成份信息！");
//                }else

                Intent intent1 = new Intent(JGUpMainActivity.this, ComAbDListActivity.class);
                startActivity(intent1);
                break;
            case R.id.btn_title_left:
                 finish();
                 break;
            case R.id.btn_up:
                if(imagePaths==null){
                    ToastUtils.showLong(JGUpMainActivity.this,"請選擇圖片！");
                }else if (tvInvalidDate.getText().toString().equals("選擇時間")||tvOpenDate.getText().toString().equals("選擇時間")){
                    ToastUtils.showLong(JGUpMainActivity.this,"請選擇正確時間！");
                }else if (address.equals("請選擇！")){
                    ToastUtils.showLong(JGUpMainActivity.this,"請選擇地址！");
                }else{
                    btnUp.setClickable(false);
                    upMessage();
                }
                break;
//            case R.id.tv_nongdu:
//                if ((int)(Float.valueOf(1)/(Float.valueOf(jxs)/(Float.valueOf(jwater)*1000)))<=100) {
//                    tvNongDu.setTextColor(getResources().getColor(R.color.blank));
//                    tvNongDu.setText("1：" + ((int) (Float.valueOf(1) / (Float.valueOf(jxs) / (Float.valueOf(jwater) * 1000)))));
//                }else{
//                    tvNongDu.setText("配比異常請確認！");
//                    tvNongDu.setTextColor(getResources().getColor(R.color.color_d73d19));
//                }
//                break;
        }
    }
    private class GridAdapter extends BaseAdapter {
        private ArrayList<String> listUrls;

        public GridAdapter(ArrayList<String> listUrls) {
            this.listUrls = listUrls;
        }

        @Override
        public int getCount() {
            if (listUrls.size() == 3) {
                return 3;
            } else {
                return listUrls.size() + 1;
            }

        }

        @Override
        public String getItem(int position) {
            return listUrls.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView;
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.item_image, null);
                imageView = (ImageView) convertView.findViewById(R.id.imageView);
                convertView.setTag(imageView);
                // 重置ImageView宽高
//                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(columnWidth, columnWidth);
//                imageView.setLayoutParams(params);
            } else {
                imageView = (ImageView) convertView.getTag();
            }
            if (position == listUrls.size()) {
                imageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.icon_addpic_unfocused));
                if (position == 3) {
                    imageView.setVisibility(View.GONE);
                }
            } else {
                Glide.with(JGUpMainActivity.this)
                        .load(new File(getItem(position)))
                        .placeholder(R.mipmap.default_error)
                        .error(R.mipmap.default_error)
                        .centerCrop()
                        .crossFade()
                        .into(imageView);
            }
            return convertView;
        }
    }

    private void worningAlert(String msg, final int type) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示信息")
                .setMessage(msg)
                .setCancelable(false)
                .setPositiveButton("確認", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // TODO Auto-generated method stub
                        if (type==MESSAGE_TOAST){
                            finish();
                        }
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

    /**
     * 请假信息提交
     */
    private void upMessage(){

        final String url = Constants.HTTP_XS_MAKE_RECORD_UP_SERVLET;
        JsonObject object = new JsonObject();
        JsonArray photoArray = new JsonArray();

        object.addProperty("flag","xsMakeUpdate");
        object.addProperty("m_address",address);
        object.addProperty("m_device",device);
        object.addProperty("m_method",method);
        object.addProperty("m_name",name);
        object.addProperty("m_invalid_date",tvInvalidDate.getText().toString());
        object.addProperty("m_open_date",tvOpenDate.getText().toString());
        object.addProperty("m_pihao",etPihao.getText().toString());
        object.addProperty("m_chengfen",etChenFen.getText().toString());
        object.addProperty("m_amount_xs",xs.split("/")[0]);
        object.addProperty("m_amount_water",xs.split("/")[1]);
        object.addProperty("m_nongdu",tvNongDu.getText().toString());
        object.addProperty("m_unit",FoxContext.getInstance().getDep());
        object.addProperty("m_code",FoxContext.getInstance().getLoginId());
        object.addProperty("m_worker",FoxContext.getInstance().getName());
        object.addProperty("m_date",tvDate.getText().toString());

        for (int i = 0; i < imagePaths.size(); i++) {
            File pictureFile = new File(imagePaths.get(i)); //通過路徑獲取檔
//            fileMap.put("file" + i, pictureFile);//添加第一個文件
            final String pic_path = imagePaths.get(i);
            String sign_dir = Environment.getExternalStorageDirectory() + File.separator + "YanFoxconn" + File.separator + "Photos";
            String _path =  sign_dir + File.separator  + System.currentTimeMillis() +i+ ".jpg";
            //getFilesDir().getAbsolutePath()+"compressPic.jpg";
            //调用压缩图片的方法，返回压缩后的图片path
            final String compressImage = ImageZipUtils.compressImage(pic_path, _path, 50);
            String picBase64Code = ImageZipUtils.imageToBase64(compressImage);
            JsonObject jsonObject = new JsonObject();
            jsonObject.addProperty("file", picBase64Code);
            photoArray.add(jsonObject);
        }
        object.add("photo", photoArray);

        new Thread() {
            @Override
            public void run() {
                //把网络访问的代码放在这里
                try {
                    showDialog();
                    Log.e("---------", "==url===" + url);
                    String result = HttpConnectionUtil.doPostJsonObject(url, object);
                    Log.e("---------", "==result===" + result);
                    if (result != null) {
                        dismissDialog();
                        Log.e("---------", "result==fff===" + result);
                        JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                        String errCode = jsonObject.get("errCode").getAsString();
                        if (errCode.equals("200")) {
                            Message message = new Message();
                            message.what = MESSAGE_TOAST;
                            message.obj = jsonObject.get("errMessage").getAsString();
                            mHandler.sendMessage(message);

                        } else{
                            Log.e("-----------", "result==" + result);
                            Message message = new Message();
                            message.what = MESSAGE_TOAST;
                            message.obj = jsonObject.get("errMessage").getAsString();
                            mHandler.sendMessage(message);
                        }
                    }else{
                        Message message = new Message();
                        message.what = MESSAGE_NOT_NET;
                        mHandler.sendMessage(message);

                    }

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    FileUtil.deletePhotos(JGUpMainActivity.this);
                }
            }
        }.start();
    }


}
